package
{
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileFilter;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;

	public class FileUtils
	{
		public static function getURI( url:String ):String
		{
			url = url.replace( /\\/g, "/" );
			url = url.replace( ":", "|" );
			url = "file:///" + url;
			return encodeURI(url);
		}
		
		public static function saveAndOpen( path:String, data:* ):void
		{
			var file:File = writeToFile( path, data );
			
			setTimeout( function open():void{file.openWithDefaultApplication();}, 500 );
		}
		/**
		 * 写文件操作 
		 * @param path 文件路径
		 * @param data 要写入的数据，可以是String, ByteArray
		 * 
		 */		
		public static function writeToFile( path:String, data:* ):File
		{
			var file:File = new File(path);
			var fs:FileStream = new FileStream();
			fs.open( file, FileMode.WRITE );
			if( data is String )
			{
				fs.writeMultiByte( data as String, "utf-8" );
			}
			else if( data is ByteArray )
			{
				fs.writeBytes( data as ByteArray );
			}
			fs.close();
			
			return file;
		}
		
		/**
		 * 读取文件 
		 * @param path 文件路径
		 * @param format 读取格式，0：String， 1：ByteArray
		 * @return 
		 * 
		 */		
		public static function readFile( path:String, format:int ):*
		{
			var ret:* = null;
			var file:File = new File(path);
			if( file.isDirectory || !file.exists ) return null;
			
			var fs:FileStream = new FileStream();
			fs.open( file, FileMode.READ );
			if( format==0 )
			{
				ret = fs.readUTFBytes( file.size );
			}
			else if( format==1 )
			{
				ret = new ByteArray();
				fs.readBytes( ret );
			}
			fs.close();
			
			return ret;
		}
		
		public static function browseForOpen( onSelectedFun:Function, title:String="请选择要打开的文件", extend:String="swf" ):void
		{
			var f:File = new File();
			var fun1:Function = function onSelect( e:Event ):void
			{
				f.removeEventListener( Event.SELECT, fun1 );
				f.removeEventListener( Event.CANCEL, fun2 );
				if( onSelectedFun != null ) onSelectedFun( f.nativePath );
			};
			var fun2:Function = function onCancel( e:Event ):void
			{
				f.removeEventListener( Event.CANCEL, fun2 );
				f.removeEventListener( Event.SELECT, fun1 );
			};
			f.addEventListener( Event.SELECT, fun1 );
			f.addEventListener( Event.CANCEL, fun2 );
			f.browseForOpen( title, getFileFilter(extend) );
		}
		
		private static function getFileFilter( extend:String ):Array
		{
			if( extend=="swf" )
			{
				return [new FileFilter("SWF", "*.swf")];
			}
			else if( extend=="jpg" )
			{
				return [new FileFilter("JPG", "*.jpg")];
			}
			return null;
		}
	}
}



















